package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.dialog.DeleteAddressDialog;
import com.shwread.android.ui.dialog.DialogCommonOkListenet;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import logic.bean.UserAddressInfo;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import logic.util.Utils;


/**
 * 选择收货地址列表
 *
 * @author xuzhijun
 * @date 2015年3月18日
 */
public class AddressInfoListActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private Context context;
    //	public static final String    FROM_TYPE   = "fromType";
    //	public static final String    UPDATEINFO  = "updateInfo";
    //	public static final int       ADD_TYPE    = 0;
    //	public static final int       UPDATE_TYPE = 1;

    private TextView tvTitle;
    private Button btnHome;
    private Button btnBack;
    private ListView listView;

    private Button btnAddNewAddress;

    private AddressListAdapater adapter;
    private Map<String, Boolean> selected = new HashMap<String, Boolean>();  //保存选中的状态
    private UserAddressInfo addressInfo;
    private List<UserAddressInfo> addressData = new ArrayList<UserAddressInfo>();
    private int flag;                                          //
    private RelativeLayout rlay_loading;
    private AnimationDrawable animationDrawable;
    private ImageView loadingImg;
    private boolean isNoAdress = false;

    @Override
    public Handler getUIHandler() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.address_info_list);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            addressInfo = (UserAddressInfo) bundle.get("addressInfo");
        }
        context = this;
        initView();
        setListener();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (NetworkUtil.isNetAvailable(context)) {
            startLoading();
            getData();
        } else {
            new NoNetDialog(context);
        }
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(getResources().getString(R.string.address_title));
        btnHome = (Button) findViewById(R.id.common_header_home);
        btnHome.setVisibility(View.VISIBLE);
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        btnAddNewAddress = (Button) findViewById(R.id.address_info_add_btn);

        listView = (ListView) findViewById(R.id.address_info_listview);
        listView.setVisibility(View.GONE);
        adapter = new AddressListAdapater();
        listView.setAdapter(adapter);

        rlay_loading = (RelativeLayout) findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
    }

    private void setListener() {
        btnHome.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        btnAddNewAddress.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_home:
                //				Utils.ToastShow(AddressInfoListActivity.this, "点击了返回主页");
                //				startActivity(new Intent(AddressInfoListActivity.this, MainActivity.class));
                BaseSimpleActivity.gotoMainActivity();
                break;
            case R.id.common_header_back:
                AddressInfoListActivity.this.finish();
                break;
            case R.id.address_info_add_btn:
                //				Intent intent = new Intent(AddressInfoListActivity.this, AddressInfoEditActivity.class);

                Intent addressInfoEditIntent = new Intent(AddressInfoListActivity.this, AddressInfoEditActivity.class);
                addressInfoEditIntent.putExtra(DefaultConsts.EDIT_ADDRESS_FROM_TYPE, DefaultConsts.EDIT_ADDRESS_ADD_TAG);
                startActivityForResult(addressInfoEditIntent, DefaultConsts.EDIT_ADDRESS_NO_ADDRESS_REQ_CODE);
                break;
        }
    }

    /**
     * 开始加载动画
     */
    private void startLoading() {
        rlay_loading.setVisibility(View.VISIBLE);
        loadingImg.setBackgroundResource(R.drawable.home_progress);
        animationDrawable = (AnimationDrawable) loadingImg.getBackground();
        animationDrawable.start();
    }

    /**
     * 停止加载动画
     */
    private void stopLoading() {
        rlay_loading.setVisibility(View.GONE);
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DefaultConsts.EDIT_ADDRESS_NO_ADDRESS_REQ_CODE) {
            if (addressData.size() == 0) {
                isNoAdress = true;
            }
        }
        if (requestCode == DefaultConsts.ECOMMERCE_TAG_ADDRESS_EDIT_UPDATE && resultCode == RESULT_OK) {
            //修改地址
            Intent returnIntent = getIntent();
            if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == ConfirmOrderActivity.ADDRESS_REQUEST_CODE) {
                returnIntent.putExtra(DefaultConsts.ADDRESS_LIST, (UserAddressInfo) data.getExtras().get(DefaultConsts.ADDRESS_LIST));
                setResult(ConfirmOrderActivity.ADDRESS_FROM_CODE, returnIntent);
            }
//			else if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == NewOrderIndexPage.newOrderIndexPage)
//			{
//				if (addressInfo.getAddressId() == ((UserAddressInfo) data.getExtras().get(DefaultConsts.ADDRESS_LIST)).getAddressId())
//				{
//					Bundle bundle = new Bundle();
//					bundle.putSerializable(DefaultConsts.ADDRESS_LIST, (UserAddressInfo) data.getExtras().get(DefaultConsts.ADDRESS_LIST));
//					returnIntent.putExtra(BUNDLE_DATA, bundle);
//					setResult(RESULT_OK, returnIntent);
//				}
//			}
        }
    }

    /**
     * 获取收货地址
     */
    private void getData() {
        NewActionHelp.qryUserDeliveryAddress(context, false, new GetUserDeliveryAddressAction());
    }

    /**
     * 设置默认地址
     *
     * @param addressId
     */
    private void setAddressDefault(long addressId) {
        startLoading();
        NewActionHelp.updateUserDeliveryAddress(context, addressId, true, "", "", null, "", new setAddressDefaultListener());
    }

    /**
     * 删除地址
     *
     * @param addressIds
     * @param position
     */
    private void deleteAddress(String addressIds, int position) {
        if (NetworkUtil.isNetAvailable(context)) {
            NewActionHelp.delUserDeliveryAddress(context, addressIds, new deleteAddressAction(position));
        } else {
            new NoNetDialog(context);
        }
    }

    /********************************************************************************/

    class GetUserDeliveryAddressAction
            extends
            ObjectHttpResponseHandler<List<UserAddressInfo>> {

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#onFailure(int,
         * org.apache.http.Header[], java.lang.String, java.lang.Throwable)
         */
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.e(responseString, throwable);
            stopLoading();
            listView.setVisibility(View.GONE);
        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#onSuccess(int,
         * org.apache.http.Header[], java.lang.Object, java.lang.String)
         */
        @Override
        public void onSuccess(int statusCode, Header[] headers, List<UserAddressInfo> object, String responseString) {
            Logger.d(responseString);
            stopLoading();

            if (object.size() > 0) {
                if (flag != 2) {
                    if (addressData.size() > 0) addressData.clear();
                    addressData.addAll(object);
                } else {
                    addressData.addAll(object);
                }
                listView.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
            } else {
                listView.setVisibility(View.GONE);
            }
            if (addressData.size() == 1 && isNoAdress) {
                Intent returnIntent = getIntent();
                if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == ConfirmOrderActivity.ADDRESS_REQUEST_CODE) {
                    returnIntent.putExtra(DefaultConsts.ADDRESS_LIST, addressData.get(0));
                    setResult(ConfirmOrderActivity.ADDRESS_FROM_CODE, returnIntent);
                    AddressInfoListActivity.this.finish();
                }
            }
        }

        /*
         * (non-Javadoc)
         * @see com.shwread.http.base.ObjectHttpResponseHandler#getType()
         */
        @Override
        public Type getType() {
            return new TypeToken<List<UserAddressInfo>>() {
            }.getType();
        }

    }

    private class setAddressDefaultListener
            extends
            ObjectHttpResponseHandler<Object> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode < 1000) {

                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }
            stopLoading();

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, Object object, String responseString) {
            System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
            Utils.showToast(context, "设置成功");
            getData();
            stopLoading();
            //			adapter.notifyDataSetChanged();
        }

        @Override
        public Type getType() {
            return new TypeToken<Object>() {
            }.getType();
        }

    }

    private class deleteAddressAction
            extends
            ObjectHttpResponseHandler<Object> {
        private int deletePosition;

        public deleteAddressAction(int deletePosition) {
            super();
            this.deletePosition = deletePosition;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode < 1000) {

                Utils.ToastShow(context, "网络错误");
            } else {
                Utils.ToastShow(context, "请求出错");
            }

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, Object object, String responseString) {
            System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
            Utils.showToast(context, "删除成功");
            if (addressInfo != null && addressInfo.getAddressId() == addressData.get(deletePosition).getAddressId()) {
                setResult(ConfirmOrderActivity.ARRESS_DELETE_SELECTED);
            }
//			if (NewOrderIndexPage.addressInfo != null && NewOrderIndexPage.addressInfo.getAddressId() == addressData.get(deletePosition).getAddressId())
//			{
//				NewOrderIndexPage.addressChanged = true;
//			}
            addressData.remove(deletePosition);
            Intent returnIntent = getIntent();
            if (addressData.size() > 0) {
                UserAddressInfo addressInfo = addressData.get(0);
                setAddressDefault(addressInfo.getAddressId());
//				if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == NewOrderIndexPage.newOrderIndexPage)
//				{
//					Bundle bundle = new Bundle();
//					bundle.putSerializable(DefaultConsts.ADDRESS_LIST, addressData.get(0));
//					returnIntent.putExtra(BUNDLE_DATA, bundle);
//					setResult(RESULT_OK, returnIntent);
//				}
            } else {
//				if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == NewOrderIndexPage.newOrderIndexPage)
//				{
//					Bundle bundle = new Bundle();
//					bundle.putSerializable(DefaultConsts.ADDRESS_LIST, null);
//					returnIntent.putExtra(BUNDLE_DATA, bundle);
//					setResult(RESULT_OK, returnIntent);
//				}
                adapter.notifyDataSetChanged();
            }
            //			adapter.notifyDataSetChanged();
        }

        @Override
        public Type getType() {
            return new TypeToken<Object>() {
            }.getType();
        }

    }

    /**********************************************************************************/

    /**********************************************************************************/

    private class AddressListAdapater
            extends
            BaseAdapter {
        private AddressViewHolder holder;

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return (addressData == null || addressData.size() == 0) ? 0 : addressData.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return (addressData == null || addressData.size() == 0) ? "" : addressData.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            holder = new AddressViewHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(AddressInfoListActivity.this).inflate(R.layout.address_info_item, parent, false);
                holder.tvName = (TextView) convertView.findViewById(R.id.address_info_item_name_tv);
                holder.tvPhone = (TextView) convertView.findViewById(R.id.address_info_item_phone_tv);
                holder.tvAddress = (TextView) convertView.findViewById(R.id.address_info_item_address_tv);
                holder.ivEdit = (ImageView) convertView.findViewById(R.id.address_info_item_edit_iv);
                holder.IvDelete = (ImageView) convertView.findViewById(R.id.address_info_item_delete_iv);
                holder.layAddress = (RelativeLayout) convertView.findViewById(R.id.address_info_item_lay);
                convertView.setTag(holder);
            } else {
                holder = (AddressViewHolder) convertView.getTag();
            }
            final UserAddressInfo info = (UserAddressInfo) getItem(position);
            holder.tvName.setText(Utils.isEmpty(info.getName()) ? "" : info.getName());
            String add = info.getProvinceName() + info.getCityName() + info.getAreaName() + info.getDetailAddress();
            holder.tvAddress.setText(Utils.isEmpty(add) ? "" : add);
            holder.tvPhone.setText(Utils.isEmpty(info.getPhone()) ? "" : info.getPhone());
            holder.btnSetDefault = (TextView) convertView.findViewById(R.id.address_info_item_select_tv);
            holder.btnSetDefault.setSelected(info.isDefault());

            holder.btnSetDefault.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    //					for (String key : selected.keySet())
                    //					{
                    //						selected.put(key, false);
                    //					}
                    //					selected.put(addressData.get(position).toString(), true);

                    //					holder.btnSetDefault.setSelected(true);
                    setAddressDefault(info.getAddressId());
                    //					adapter.notifyDataSetChanged();
                }

            });
            holder.layAddress.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    //					Utils.ToastShow(AddressInfoListActivity.this, addressData.get(position).getName() + " " + position);
                    Intent returnIntent = getIntent();
                    if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == ConfirmOrderActivity.ADDRESS_REQUEST_CODE) {
                        returnIntent.putExtra(DefaultConsts.ADDRESS_LIST, info);
                        setResult(ConfirmOrderActivity.ADDRESS_FROM_CODE, returnIntent);
                        AddressInfoListActivity.this.finish();
                    }
//					else if (returnIntent.getExtras() != null && returnIntent.getExtras().getInt(DefaultConsts.FROM_TYPE) == NewOrderIndexPage.newOrderIndexPage)
//					{
//						Bundle bundle = new Bundle();
//						bundle.putSerializable(DefaultConsts.ADDRESS_LIST, info);
//						returnIntent.putExtra(BUNDLE_DATA, bundle);
//						setResult(RESULT_OK, returnIntent);
//						AddressInfoListActivity.this.finish();
//					}

                }
            });
            holder.IvDelete.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    DeleteAddressDialog dialog = new DeleteAddressDialog(AddressInfoListActivity.this, new DialogCommonOkListenet() {

                        @Override
                        public void clickOk() {
                            UserAddressInfo addressInfo = addressData.get(position);
                            long addressId = addressInfo.getAddressId();
                            deleteAddress(Long.toString(addressId), position);
                            //							addressData.remove(position);
                            //							UserAddressInfo addressInfo = addressData.get(position);
                            //							long addressId = addressInfo.getAddressId();
                            //							adapter.notifyDataSetChanged();

                        }
                    });
                    dialog.show();
                }
            });
            holder.ivEdit.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
//					if (NewOrderIndexPage.addressInfo != null && NewOrderIndexPage.addressInfo.getAddressId() == addressData.get(position).getAddressId())
//					{
//						NewOrderIndexPage.addressChanged = true;
//					}
                    Intent intent = new Intent(AddressInfoListActivity.this, AddressInfoEditActivity.class);

                    intent.putExtra(DefaultConsts.EDIT_ADDRESS_FROM_TYPE, DefaultConsts.EDIT_ADDRESS_UPDATE_TAG);
                    intent.putExtra(DefaultConsts.EDIT_ADDRESS_UPDATEINFO, addressData.get(position));
                    //										startActivityForResult(intent, DefaultConsts.ADDRESS_EDIT_UPDATE);
                    //					startActivity(intent);
                    startActivityForResult(intent, DefaultConsts.ECOMMERCE_TAG_ADDRESS_EDIT_UPDATE);
                }
            });

            //			boolean res = false;
            //			if (selected.get(addressData.get(position).toString()) == null)
            //			{
            //				selected.put(addressData.get(position).toString(), res);
            //			}
            //			else if (selected.get(addressData.get(position).toString()) == false)
            //			{
            //				selected.put(addressData.get(position).toString(), false);
            //			}
            //			else
            //			{
            //				res = true;
            //			}
            //
            //			holder.btnSetDefault.setSelected(res);

            return convertView;
        }
    }

    private class AddressViewHolder {
        public TextView tvName;
        public TextView tvPhone;
        public TextView tvAddress;
        public ImageView ivEdit;
        public ImageView IvDelete;
        public TextView btnSetDefault;
        public RelativeLayout layAddress;

    }

}
